import {
	Encrypt,
	Decrypt
}
from '@/util/aesUtil.js'
import Rsa from './rsa.js';
import qs from 'qs'



const BASE_URL = 'https://api.shengzaixx.com/'

export const myRequest = (options) => {
	let accessToken = uni.getStorageSync('token')
	let channelCode = uni.getStorageSync('channelCode')
	let jcid = uni.getStorageSync('jcid')
	let bdVid = uni.getStorageSync('bdVid')
	
	
	const browserParameterStr = sessionStorage.getItem('BrowserAddressParameter')
	const browserParameter = browserParameterStr ? JSON.parse(browserParameterStr) : {}
	console.log(browserParameter, `地址栏参数`)
	let tokenKey = {
		'token': accessToken
	}
	let optionsDataStr = Object.assign({},browserParameter, options.data, tokenKey)
	console.log(optionsDataStr, `${options.url}---Api参数`)
	let dataStr = JSON.stringify(optionsDataStr)

	console.log('channelCode',channelCode)
	let randomStr = getRandomString(32)	
	let aesss = Encrypt(dataStr, randomStr, '0392039203920300')
	// console.log(aesss)
	var base64 = new Base64()
	let rsaStr = Rsa.jiami(randomStr);
	let baseRsa = base64.encode(rsaStr)
	let baseaesss = base64.encode(aesss)


	let baseMap = {
		'appId': 'hxhh5',
		'tranData': baseaesss,
		'ciphertext': baseRsa,
		"version": '1.0.1'
	}
	let system = ''
	let brand = ''
	let deviceId = ''
	let model = ''
	uni.getSystemInfo({
		success: (res) => {
			system = res.system
			brand = res.brand
			deviceId = res.deviceId
			model = res.model
		}
	})


	return new Promise((resolve, reject) => {
		uni.showLoading({
			title:'加载中...'
		})
		uni.request({
			url: BASE_URL + options.url,
			method: options.method || 'GET',
			data: baseMap || {},
			header: {
				'content-type': 'application/x-www-form-urlencoded',
				'clientType': 'h5',
				'channelCode': channelCode,
				'system':system,
				'brand':brand,
				'deviceId':deviceId,
				'model':model,
				'jcid':jcid,
				'bdVid': bdVid
			},
			// dataType:'json',


			success: (res) => {
				uni.hideLoading()
				// console.log(res);
				if (res.data.rspCode !== '0001') {
					reject()
					if (res.data.rspCode == '0002') {

						var channelCode = uni.getStorageSync('channelCode');
						uni.setStorageSync('token_mobile', "");
						uni.setStorageSync('token', '')
						
						// console.log(location.hash.replaceAll('#/', ''))
						uni.setStorageSync('islogin', false)
						uni.redirectTo({
							url: '/pages/index/index/?' + qs.stringify(browserParameter)
						})


					}

					if (res.data.rspMsg) {
						return uni.showToast({
							title: res.data.rspMsg,
							icon: 'error'

						})
					}




				} else {

					resolve(res.data.data)

				}

			},
			fail: (err) => {
				uni.showToast({
					title: '网络错误',
					icon: 'error'
				})
				reject(err)
			},
			complete: (complete) => {

				// console.log(complete.statusCode)

			}
		})
	})
}

function stringToHex(str) {
	var val = "";
	for (var i = 0; i < str.length; i++) {
		if (val == "")
			val = str.charCodeAt(i).toString(16);
		else
			val += str.charCodeAt(i).toString(16);
	}
	return val;
}

function getRandomString(len) {
	let _charStr = 'abacdefghjklmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789',
		min = 0,
		max = _charStr.length - 1,
		_str = ''; //定义随机字符串 变量
	//判断是否指定长度，否则默认长度为15
	len = len || 15;
	//循环生成字符串
	for (var i = 0, index; i < len; i++) {
		index = (function(randomIndexFunc, i) {
			return randomIndexFunc(min, max, i, randomIndexFunc);
		})(function(min, max, i, _self) {
			let indexTemp = Math.floor(Math.random() * (max - min + 1) + min),
				numStart = _charStr.length - 10;
			if (i == 0 && indexTemp >= numStart) {
				indexTemp = _self(min, max, i, _self);
			}
			return indexTemp;
		}, i);
		_str += _charStr[index];
	}
	return _str;
}


function Base64() {
	// private property
	let _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
	// public method for encoding
	this.encode = function(input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;
		input = _checkChar(input)
		input = _utf8_encode(input);
		// console.log(input);
		while (i < input.length) {
			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);
			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;
			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}
			output = output +
				_keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
				_keyStr.charAt(enc3) + _keyStr.charAt(enc4);
		};
		output = output.replace('+', '%2B'); // 这个后台识别不了+，所以替换了一下，这个也可以不用替换，视实际情况定
		return output;
	};

	// public method for decoding
	this.decode = function(input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;
		if (typeof(input) == String) {
			input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
		} else {
			return input
		}
		while (i < input.length) {
			enc1 = _keyStr.indexOf(input.charAt(i++));
			enc2 = _keyStr.indexOf(input.charAt(i++));
			enc3 = _keyStr.indexOf(input.charAt(i++));
			enc4 = _keyStr.indexOf(input.charAt(i++));
			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;
			output = output + String.fromCharCode(chr1);
			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}
		}
		output = _utf8_decode(output);
		output = _returnJson(output);
		return output;
	}

	// private method for UTF-8 encoding
	let _utf8_encode = function(string) {
		string = string.replace(/\r\n/g, "\n");
		var utftext = "";
		for (var n = 0; n < string.length; n++) {
			var c = string.charCodeAt(n);
			if (c < 128) {
				utftext += String.fromCharCode(c);
			} else if ((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			} else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}

		}
		// console.log(utftext);
		return utftext;
	}

	// private method for UTF-8 decoding
	let _utf8_decode = function(utftext) {
		var string = "";
		var i = 0;
		var c1, c2, c3;
		var c = c1 = c2 = 0;
		while (i < utftext.length) {
			c = utftext.charCodeAt(i);
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			} else if ((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i + 1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			} else {
				c2 = utftext.charCodeAt(i + 1);
				c3 = utftext.charCodeAt(i + 2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
		}
		return string;
	}
	let _checkChar = function(textJson) {
		var pattern = new RegExp("[\u4E00-\u9FA5]+");
		for (let item in textJson) {
			if (pattern.test(textJson[item])) {
				textJson[item] = encodeURIComponent(textJson[item]);
			}
		}
		return JSON.stringify(textJson);
	}
	let _returnJson = function(textString) {
		let res = JSON.parse(textString);
		for (let item in res) {
			res[item] = decodeURIComponent(res[item]);
		}
		return res;
	}
}


function b64EncodeUnicode(str) {
	return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
		return String.fromCharCode('0x' + p1);
	}));
}
